package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.RateLimiter;

/**
 * 非阻塞式获取令牌
 *
 * @author yangyunjiao
 */
public class NonBlockingRateLimiterExample {
    public static void main(String[] args) {
        RateLimiter rateLimiter = RateLimiter.create(2.0);

        for (int i = 0; i < 10; i++) {
            // 尝试获取令牌，立即返回结果
            if (rateLimiter.tryAcquire()) {
                System.out.println("成功获取令牌，执行任务: " + i);
                processRequest(i);
            } else {
                System.out.println("无法获取令牌，任务被拒绝: " + i);
            }

            try {
                Thread.sleep(200); // 模拟间隔
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    private static void processRequest(int id) {
        System.out.println("处理请求: " + id + " | 时间: " + System.currentTimeMillis());
    }
}
